package com.jishaokang.util;

import com.alibaba.fastjson.JSON;
import com.jishaokang.model.dto.Live;
import com.jishaokang.model.vo.LiveVO;
import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by NANA_Final on 2019/7/1.
 */
@Component
public class LiveUtil {

    public String connectLiveServer(LiveVO live) throws IOException {
        ConnectLiveJson connectLiveJson = new ConnectLiveJson("create_live",live.getLiveName(),live.getTeacherName(),live.getLiveId());
        String jsonString = JSON.toJSONString(connectLiveJson);
        Connection.Response response = Jsoup.connect("http://182.92.1.116:3000/livecreator")
                .header("Content-Type", "application/json")
                .requestBody(jsonString)
                .method(Connection.Method.POST)
                .execute();
        String body = response.body();
        System.out.println(body);
        String liveUrl = null;
        String regex = "\"liveUrl\": \"(.*?)\"";
        Matcher matcher = Pattern.compile(regex).matcher(body);
        while (matcher.find()) {
            liveUrl = matcher.group(1);
        }
        System.out.println(liveUrl);
        return liveUrl;
    }
    public void closeLiveServer(Live live) throws IOException {
        CloseLiveJson closeLiveJson = new CloseLiveJson("close_live",live.getLiveId());
        String jsonString = JSON.toJSONString(closeLiveJson);
        Connection.Response response = Jsoup.connect("")
                .header("Content-Type", "application/json")
                .requestBody(jsonString)
                .method(Connection.Method.POST)
                .execute();
        String body = response.body();
        System.out.println(body);

    }

    private class ConnectLiveJson {
        String event;
        String liveName;
        String teacherName;
        Integer liveId;

        ConnectLiveJson(String event,String liveName,String teacherName,int liveId){
            this.event = event;
            this.liveName = liveName;
            this.teacherName = teacherName;
            this.liveId = liveId;
        }
    }

    private class CloseLiveJson {
        String event;
        Integer liveId;

        CloseLiveJson(String event,int liveId){
            this.event = event;
            this.liveId = liveId;
        }
    }
}
